package com.rdc.example.service.impl;

import com.rdc.example.bean.PageBean;
import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.ColumnDTO;
import com.rdc.example.dao.ColumnDao;
import com.rdc.example.dao.SongDao;
import com.rdc.example.dao.UserDao;
import com.rdc.example.dao.impl.ColumnDaoImpl;
import com.rdc.example.dao.impl.SongDaoImpl;
import com.rdc.example.dao.impl.UserDaoImpl;
import com.rdc.example.entity.Column;
import com.rdc.example.entity.User;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class ColumnServiceImpl implements com.rdc.example.service.ColumnService {

    ColumnDao columnDao = new ColumnDaoImpl();
    UserDao userDao = new UserDaoImpl();
    SongDao songDao = new SongDaoImpl();

    @Override
    public Result insertColumn(ColumnDTO columnDTO) throws Exception {
            Column columnEntity = convertToEntity(columnDTO);
            boolean register = columnDao.insert(columnEntity);
            return register  ? Result.success("创建成功", null)
                    : Result.fail("创建失败", null);
    }

    @Override
    public Result deleteColumn(Integer columnId) throws Exception {
        if(columnId == null) {
            return Result.fail("columnId不可为空", null);
        }
        boolean register = columnDao.deleteById(columnId);
        return register  ? Result.success("删除成功", null)
                : Result.fail("删除失败", null);
    }

    @Override
    public Result deleteColumn(Integer userId, Integer columnId) throws Exception {
        if (userId == null || columnId == null) {
            return Result.fail("userId或columnId不为空", null);
        }
        //获取用户
        User user=userDao.getUserById(userId);
        //获取歌曲
        Column column =columnDao.getColumnById(columnId);
        //权限检测 是不是自己的，是不是管理员
        if(!user.getId().equals(column.getUserId())&&user.getUserType()!=3){
            return Result.fail("权限不足", null);
        }
        //对应歌曲所属专辑设为空
        songDao.removeColumnAll(columnId);
        //删除专辑
        boolean deleteColumn = columnDao.deleteById(columnId);
        return deleteColumn ? Result.success("删除成功", null)
                : Result.fail("删除失败", null);
    }

    @Override
    public Result updateColumn(ColumnDTO columnDTO) throws Exception {
        Column columnEntity = convertToEntity(columnDTO);
        boolean register = columnDao.update(columnEntity);
        return register ? Result.success("修改成功", null)
                : Result.fail("修改失败", null);
    }

    @Override
    public Result inColumn(Integer columnId, Integer songId) throws Exception {
        if(columnId == null || songId == null) {
            return Result.fail("columnId,songId不可为空", null);
        }
        boolean register = songDao.addColumn(songId,columnId);
        return register  ? Result.success("添加成功", null)
                : Result.fail("添加失败", null);
    }

    @Override
    public Result outColumn(Integer songId) throws Exception {
        if( songId == null) {
            return Result.fail("songId不可为空", null);
        }
        boolean register = songDao.removeColumn(songId);
        return register  ? Result.success("移除成功", null)
                : Result.fail("移除失败", null);
    }







    @Override
    public PageBean<ColumnDTO> getColumnListByUserId(Integer userId, Integer currentPage, Integer pageSize) throws Exception {
        if(userId == null || currentPage == null || pageSize == null) {
            return null;
        }
        Integer pageBegin = (currentPage - 1) * pageSize;
        // 调用 dao 获取数据
        List<Column> columnList = columnDao.getColumnListByPageAndUserId(userId, pageBegin, pageSize);
        Integer totalCount = columnDao.countColumnByUserId(userId);
        // 封装 PageBean
        PageBean<ColumnDTO> pageBean = new PageBean<>();
        pageBean.setTotalCount(totalCount);
        pageBean.setRows(convertAndEnrichColumns(columnList));
        return pageBean;
    }

    @Override
    public PageBean<ColumnDTO> searchColumnsByTitle(String keyword, Integer currentPage, Integer pageSize) throws Exception {
        Integer pageBegin = (currentPage - 1) * pageSize;
        // 调用 dao
        List<Column> columnList = columnDao.searchColumnsByTitle(keyword, pageBegin, pageSize);
        Integer totalCount = columnDao.countSearchColumnsByTitle(keyword);
        // 封装 PageBean
        PageBean<ColumnDTO> pageBean = new PageBean<>();
        pageBean.setTotalCount(totalCount);
        pageBean.setRows(convertAndEnrichColumns(columnList));
        return pageBean;
    }





    private List<ColumnDTO> convertAndEnrichColumns(List<Column> columnEntityList) throws SQLException {
        List<ColumnDTO> dtos = new ArrayList<>();
        Set<Integer> userIds = columnEntityList.stream()
                .map(Column::getUserId)
                .collect(Collectors.toSet());
        UserDaoImpl userDao = new UserDaoImpl();
        Map<Integer, User> userMap = userDao.getUsersByIds(userIds);
        // 转换并填充作者信息
        for (Column entity : columnEntityList) {
            ColumnDTO dto = convertToDto(entity);
            User user = userMap.get(entity.getUserId());
            if (user != null) {
                dto.setUserName(user.getUserName());
            } else {
                dto.setUserName("未知");
                System.err.println("用户不存在: userId=" + entity.getUserId());
            }
            dtos.add(dto);
        }
        return dtos;
    }


    private ColumnDTO convertToDto(Column entity) {
        ColumnDTO dto = new ColumnDTO();
        dto.setId(entity.getId());
        dto.setUserId(entity.getUserId());
        dto.setName(entity.getName());
        dto.setCreatedAt(entity.getCreatedAt());
        return dto;
    }

    private Column convertToEntity(ColumnDTO dto) {
        Column entity = new Column();
        entity.setId(dto.getId());
        entity.setUserId(dto.getUserId());
        entity.setName(dto.getName());
        entity.setCreatedAt(dto.getCreatedAt());
        return entity;
    }

    private List<ColumnDTO> convertToDtoList(List<Column> columnEntityList) {
        List<ColumnDTO> dtos = new ArrayList<>();
        for (Column entity : columnEntityList) {
            ColumnDTO dto = convertToDto(entity);
            dtos.add(dto);
        }
        return dtos;
    }
}
